# -*- coding: utf-8 -*-
from datetime import datetime, timedelta

from odoo import models, fields, api,_
from odoo.exceptions import ValidationError, UserError
from odoo.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT


class HROvertime(models.Model):
    _name = 'hr.overtime'
    _description = u'加班单'
    _order = 'sheet_id, apply_date desc, department_id,barcode'


    resource_calendar_id = fields.Many2one('resource.calendar', compute='compute_resource_calendar_id', store=True,string=u'班别')
    employee_type = fields.Selection([
        ('1', '月薪'),
        ('2', '日薪'),
        ('3', '小时工')
    ], string=u'职工类型',related='employee_id.employee_type',readonly=True)

    @api.depends('apply_date', 'employee_id')
    def compute_resource_calendar_id(self):
        for record in self:
            record.resource_calendar_id = record.employee_id.get_current_calendar_id(record.apply_date)

    _sql_constraints = [
        ('name_uniq', 'unique (name)', "单号我必须唯一!"),
    ]

    state = fields.Selection([
        ('draft', u'草稿'),
        ('cancel', u'取消'),
        ('to approve', u'待审核'),
        ('rejected', u'拒绝'),
        ('done', u'完成'),
    ], string=u"预报状态", related='sheet_id.state',store=True)

    show_state = fields.Selection([
        ('draft', u'草稿'),
        ('cancel', u'取消'),
        ('to approve', u'待审核'),
        ('rejected', u'拒绝'),
        ('done', u'完成'),
    ], string=u"状态", compute='compute_show_state')

    def compute_show_state(self):
        for r in self:
            if r.sheet_id.real_sheet_ids:
                r.show_state = r.sheet_id.real_sheet_ids[0].state
            else:
                r.show_state=r.sheet_id.state

    real_state = fields.Selection([
        ('before','预报中'),
        ('draft', u'草稿'),
        ('cancel', u'取消'),
        ('to approve', u'待审核'),
        ('rejected', u'拒绝'),
        ('done', u'完成'),
    ], string=u"实报状态",compute='compute_real_state',store=True)
    @api.depends('sheet_id.real_sheet_ids.state')
    def compute_real_state(self):
        for r in self:
            if r.sheet_id.real_sheet_ids:
                r.real_state=r.sheet_id.real_sheet_ids[0].state
            else:
                r.real_state='before'

    to_approve_user_id=fields.Many2one('res.users',compute='compute_to_approve_user_id',string=u'待审核人')
    def compute_to_approve_user_id(self):
        for r in self:
            if r.sheet_id.to_approve_user_id:
                r.to_approve_user_id =r.sheet_id.to_approve_user_id
            elif r.sheet_id.real_sheet_ids:
                r.to_approve_user_id=r.sheet_id.real_sheet_ids[0].to_approve_user_id.id
            else:
                r.to_approve_user_id=False


    overtime_sheet_type=fields.Selection([
        ('1','预报'),
        ('2', '实报'),
    ],compute='compute_overtime_sheet_type',store=True,string=u'阶段')
    @api.depends('sheet_id.real_sheet_ids')
    def compute_overtime_sheet_type(self):
        for r in self:
            if r.sheet_id.real_sheet_ids:
                r.overtime_sheet_type='2'
            else:
                r.overtime_sheet_type='1'



    # _sql_constraints = [
    #     ('name_uniq', 'unique (employee_id,apply_date)', "员工每天只能申请一次加班!"),
    # ]

    datetime_start = fields.Datetime(compute='get_real_checkin_time')
    datetime_start_format = fields.Char(compute='get_real_checkin_time',help='实际开始格式化了一下',string=u'开始')
    datetime_end = fields.Datetime(compute='get_real_checkin_time')
    datetime_end_format = fields.Char(compute='get_real_checkin_time',string=u'结束')

    real_time_start = fields.Selection([
        ('0', '0:00'), ('0.5', '0:30'),
        ('1', '1:00'), ('1.5', '1:30'),
        ('2', '2:00'), ('2.5', '2:30'),
        ('3', '3:00'), ('3.5', '3:30'),
        ('4', '4:00'), ('4.5', '4:30'),
        ('5', '5:00'), ('5.5', '5:30'),
        ('6', '6:00'), ('6.5', '6:30'),
        ('7', '7:00'), ('7.5', '7:30'),
        ('8', '8:00'), ('8.5', '8:30'),
        ('9', '9:00'), ('9.5', '9:30'),
        ('10', '10:00'), ('10.5', '10:30'),
        ('11', '11:00'), ('11.5', '11:30'),
        ('12', '12:00'), ('12.5', '12:30'),
        ('13', '13:00'), ('13.5', '13:30'),
        ('14', '14:00'), ('14.5', '14:30'),
        ('15', '15:00'), ('15.5', '15:30'),
        ('16', '16:00'), ('16.5', '16:30'),
        ('17', '17:00'), ('17.5', '17:30'),
        ('18', '18:00'), ('18.5', '18:30'),
        ('19', '19:00'), ('19.5', '19:30'),
        ('20', '20:00'), ('20.5', '20:30'),
        ('21', '21:00'), ('21.5', '21:30'),
        ('22', '22:00'), ('22.5', '22:30'),
        ('23', '23:00'), ('23.5', '23:30')], string='开始时间', compute='get_real_checkin_time')

    real_time_end = fields.Selection([
        ('0', '0:00'), ('0.5', '0:30'),
        ('1', '1:00'), ('1.5', '1:30'),
        ('2', '2:00'), ('2.5', '2:30'),
        ('3', '3:00'), ('3.5', '3:30'),
        ('4', '4:00'), ('4.5', '4:30'),
        ('5', '5:00'), ('5.5', '5:30'),
        ('6', '6:00'), ('6.5', '6:30'),
        ('7', '7:00'), ('7.5', '7:30'),
        ('8', '8:00'), ('8.5', '8:30'),
        ('9', '9:00'), ('9.5', '9:30'),
        ('10', '10:00'), ('10.5', '10:30'),
        ('11', '11:00'), ('11.5', '11:30'),
        ('12', '12:00'), ('12.5', '12:30'),
        ('13', '13:00'), ('13.5', '13:30'),
        ('14', '14:00'), ('14.5', '14:30'),
        ('15', '15:00'), ('15.5', '15:30'),
        ('16', '16:00'), ('16.5', '16:30'),
        ('17', '17:00'), ('17.5', '17:30'),
        ('18', '18:00'), ('18.5', '18:30'),
        ('19', '19:00'), ('19.5', '19:30'),
        ('20', '20:00'), ('20.5', '20:30'),
        ('21', '21:00'), ('21.5', '21:30'),
        ('22', '22:00'), ('22.5', '22:30'),
        ('23', '23:00'), ('23.5', '23:30')], string='开始时间', compute='get_real_checkin_time')

    def get_real_checkin_time(self):
        """
        计算开始和结束时间
        data.check_in 是 减掉8小时的时间
        """
        for r in self:
            print( r.employee_id.name)
            datetime_start=0
            data = self.env['hr.attendance'].search(
                [('employee_id', '=', r.employee_id.id), ('date', '=', r.apply_date)])
            # 如果有上班打开记录
            if data and data.check_in:
                date_time = (data.check_in+timedelta(hours=8)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
                if r.sheet_id.type_id.name == '平时加班' and r.request_hour_from:
                    time = date_time.split(' ')[1]
                    date = date_time.split(' ')[0]
                    h, m, s = time.split(':')
                    if int(m) >= 30:
                        datetime_start = str(int(h)+1)
                        # 之前没有考虑0点的情况
                        if datetime_start=='24':
                            datetime_start='0'
                            now_time=datetime.strptime(date, "%Y-%m-%d")
                            date=(now_time + timedelta(days=+1)).strftime("%Y-%m-%d %H:%M:%S").split(' ')[0]
                    elif int(m)==0:
                        datetime_start = str(int(h))
                    else:
                        m = '.5'
                        datetime_start = str(float(h) + float(m))
                    t_request_hour_from=float(r.request_hour_from)
                    # 不知道为什么莫名其妙+了24
                    # 会导致加班开始时间算错 8点应该来加班，但是12点才来，加了24之后 12《32，以为他提前来加班了。
                    # 不知道哪里有问题多 加了这个段，哪天有问题再减掉吧
                    # if float(t_request_hour_from) < 12:
                    #
                    #     t_request_hour_from = float(t_request_hour_from) + 24
                    if (float(datetime_start))<float(t_request_hour_from):
                        # 如果加班开始时间小于申请时间，加班开始时间就是 申请开始时间
                        datetime_start = r.request_hour_from
                    time = datetime_start.split('.')
                    if len(time) == 1:
                        str1= date+' ' +time[0]+':00:00'
                        print (r._name,r.id,r.datetime_start,r.employee_id.name)
                        print (str1)

                        try:
                            r.datetime_start =datetime.strptime(str1, "%Y-%m-%d %H:%M:%S")
                        except Exception:
                            pass


                    else:
                        str1=date+' ' +time[0]+':30:00'
                        r.datetime_start = datetime.strptime(str1, "%Y-%m-%d %H:%M:%S")
                else:
                    r.datetime_start=data.check_in+timedelta(hours=8)
            else:
                r.datetime_start=''


            if data and data.check_out:
                r.datetime_end=data.check_out+timedelta(hours=8)

                date_time=(data.check_out+timedelta(hours=8)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
                time= date_time.split(' ')[1]
                date=date_time.split(' ')[0]
                h,m,s = time.split(':')
                if int(m)>=30:
                    m='.5'
                    r.real_time_end = str(float(h) + float(m))
                else:
                    r.real_time_end= str(int(h))
                real_time_end=float(r.real_time_end)
                if real_time_end<12:
                    real_time_end=real_time_end+24
                if float(real_time_end)<float(r.request_hour_from):
                    r.real_time_end=''
                    r.real_time_start=''
                elif float(datetime_start)>float(r.request_hour_from):
                    r.real_time_start=datetime_start
                else:
                    r.real_time_start=r.request_hour_from

            else:
                r.real_time_end=''
                r.real_time_start=''
                r.datetime_end=''
            if r.datetime_end and r.datetime_start and r.datetime_end <= r.datetime_start:

                r.datetime_end = ''
                r.datetime_start = ''
            if r.datetime_start:
                data_str=r.datetime_start.strftime(DEFAULT_SERVER_DATETIME_FORMAT).split(' ')
                time_str=data_str[1]
                print (time_str)
                r.datetime_start_format=time_str[0:5]
            else:
                r.datetime_start_format=''

            if r.datetime_end:
                data_str=r.datetime_end.strftime(DEFAULT_SERVER_DATETIME_FORMAT).split(' ')
                time_str=data_str[1]
                r.datetime_end_format=time_str[0:5]
            else:
                r.datetime_end_format=''




    is_change=fields.Boolean(string='是否调休')
    change_date=fields.Date(string=u'预计调休时间')
    def _default_employee(self):
        return self.env.context.get('default_employee_id') or self.env['hr.employee'].search([('user_id', '=', self.env.uid)], limit=1)
    employee_id=fields.Many2one('hr.employee',string=u'员工',index=True)
    barcode=fields.Char(related='employee_id.barcode',string='工号',store=True)
    user_id = fields.Many2one('res.users', default=lambda self: self.env.user,index=True)
    department_id=fields.Many2one('hr.department',string=u'部门',related='employee_id.department_id',store=True)
    apply_date=fields.Date(string='加班日期',related='sheet_id.apply_date',store=True)
    sheet_id=fields.Many2one('hr.overtime.sheet',ondelete='cascade',string=u'单号')
    type_id = fields.Many2one('hr.overtime.type',related='sheet_id.type_id', string=u'加班类别',store=True)
    hours=fields.Float()
    real_period=fields.Float(compute='compute_real_period',string=u'加班时长')

    def compute_real_period(self):

        for record in self:
            data_id = self.env['hr.attendance'].search(
                [('employee_id', '=', record.employee_id.id), ('date', '=', record.apply_date.strftime(DEFAULT_SERVER_DATETIME_FORMAT))])

            if record.apply_date and record.real_time_start and record.real_time_end:
                dayofweek = record.apply_date.weekday()
                lunch_hour = 0
                dinner_time=0
                resource_calendar_id=record.employee_id.get_current_calendar_id(record.apply_date)
                if resource_calendar_id and record.employee_id.employee_type!='1':
                    attendances = record.employee_id.get_employee_attendance(record.apply_date)
                    lunch_hour = record.employee_id.resource_calendar_id.lunch_time
                    # 月薪没加班
                    if record.employee_id.employee_type not in ('2','3'):
                        record.real_period=0
                    elif not data_id.check_out or not data_id.check_in:
                        record.real_period=0
                    #  日薪有考勤
                    elif attendances and record.employee_id.employee_type=='2' and resource_calendar_id.calendar_type  in ('1','2'):
                            hour_to = attendances[-1].hour_to
                            request_hour_to=record.real_time_end
                            if float(record.real_time_start)<float(hour_to):
                                raise UserError('%s %s 加班开始时间不能早于下班时间1' % (record.employee_id.name,record.apply_date))
                            if record.real_time_end>resource_calendar_id.dinner_hour_to:
                                if float(resource_calendar_id.dinner_hour_to)>=float(record.real_time_start):
                                    start_time=resource_calendar_id.dinner_hour_to
                                else:
                                    start_time=record.real_time_start
                                record.real_period= float(request_hour_to) - float(start_time)

                            else:
                                record.real_period=0
                    elif attendances and record.employee_id.employee_type == '2' and resource_calendar_id.calendar_type =='3':
                        hour_to = attendances[-1].hour_to
                        request_hour_to = float(record.real_time_end)
                        request_hour_from = float(record.real_time_start)
                        if float(request_hour_from) < 12:
                            request_hour_from = float(request_hour_from) + 24
                        if float(hour_to) < 12:
                            hour_to = float(hour_to) + 24
                        if float(record.request_hour_to) < 12:
                            request_hour_to = float(record.real_time_end) + 24
                        # if float(request_hour_from) > float(hour_to):
                        #     print(request_hour_from)
                        #     print (hour_to)
                        #     raise UserError('%s %s 加班开始时间不能早于下班时间' % (record.employee_id.name,record.apply_date))
                        if resource_calendar_id.dinner_hour_to:
                            compare_time = float(resource_calendar_id.dinner_hour_to)
                        else:
                            compare_time = float(attendances[-1].hour_to)
                        if compare_time < 12:
                            compare_time = compare_time + 24
                        #
                        if request_hour_to > compare_time:
                            if compare_time >= request_hour_from:
                                start_time = compare_time
                            else:
                                start_time = request_hour_from
                            record.real_period = float(request_hour_to) - float(start_time)
                            # if hour_to>13:
                            #     if resource_calendar_id.dinner_hour_to>=record.request_hour_from:
                            #         start_time=resource_calendar_id.dinner_hour_to
                            #     else:
                            #         start_time=record.request_hour_from
                            #     record.period= float(record.request_hour_to) - float(start_time)
                            # else:
                            #     if resource_calendar_id.lunch_hour_to>=record.request_hour_from:
                            #         start_time = resource_calendar_id.lunch_hour_to
                            #     else:
                            #         start_time = record.request_hour_from
                            #     record.period = float(record.request_hour_to) - float(start_time)

                    # 没考勤或者是时薪
                    elif not attendances or record.employee_id.employee_type=='3':
                        request_hour_to=record.real_time_end
                        lunch_hour_to=resource_calendar_id.lunch_hour_to
                        lunch_hour_from=resource_calendar_id.lunch_hour_from
                        if resource_calendar_id.calendar_type == '3' and float(record.real_time_end)<=float(record.real_time_start):
                            request_hour_to = float(record.real_time_end) + 24
                            lunch_hour_to=float(resource_calendar_id.lunch_hour_to)+24
                            lunch_hour_from=float(resource_calendar_id.lunch_hour_from)+24

                        if float(request_hour_to) <= float(lunch_hour_from):
                            end_time = request_hour_to
                        elif float(request_hour_to) > float(lunch_hour_from) and float(request_hour_to) <= float(
                                lunch_hour_to):
                            end_time = resource_calendar_id.lunch_hour_from
                        elif float(request_hour_to) <= float(resource_calendar_id.dinner_hour_from):
                            end_time = request_hour_to
                        else:
                            end_time = request_hour_to
                        deduct=0
                        if float(end_time) >= float(lunch_hour_to) and float(lunch_hour_from)>=float(record.real_time_start):
                            deduct += resource_calendar_id.lunch_time
                        if resource_calendar_id.dinner_hour_from and resource_calendar_id.dinner_hour_to and float(end_time) >= float(resource_calendar_id.dinner_hour_to) and float(resource_calendar_id.dinner_hour_from)>= float(record.real_time_start):
                            deduct += resource_calendar_id.dinner_time

                        if float(record.request_hour_from)<=float(lunch_hour_from):
                            start_time=record.real_time_start
                        elif float(record.real_time_start)>float(lunch_hour_from)  and float(record.real_time_start)<=float(lunch_hour_to):
                            start_time=lunch_hour_to
                        elif float(record.real_time_start)>float(lunch_hour_to) and float(record.real_time_start)<=float(resource_calendar_id.dinner_hour_from):
                            start_time=record.real_time_start
                        else:
                            start_time = record.real_time_start


                        record.real_period = float(end_time) - float(start_time)-deduct

                    # elif attendances and resource_calendar_id.calendar_type == '3':
                    #     hour_to = attendances[-1].hour_to
                    #     record.period = float(record.request_hour_to) - float(record.request_hour_from)
                else:
                    record.real_period = 0
            else:
                record.real_period = 0
            if record.real_period<0:
                record.real_period=0
            if record.real_period and record.real_period>record.period:
                record.real_period=record.period
            # if record.real_time_end:
            #     dayofweek = record.apply_date.weekday() + 1
            #     lunch_hour = 0
            #     dinner_time = 0
            #     resource_calendar_id = record.employee_id.get_current_calendar_id(record.apply_date)
            #     if resource_calendar_id:
            #         attendances = record.employee_id.resource_calendar_id.attendance_ids.filtered(
            #             lambda x: x.dayofweek == str(dayofweek))
            #         lunch_hour = record.employee_id.resource_calendar_id.lunch_time
            #         # 白班逻辑
            #         if attendances and resource_calendar_id.calendar_type == '1':
            #             hour_to = attendances[-1].hour_to
            #             if hour_to > 13:
            #                 if resource_calendar_id.dinner_hour_to >= record.request_hour_from:
            #                     start_time = resource_calendar_id.dinner_hour_to
            #                 else:
            #                     start_time = record.request_hour_from
            #                 record.real_period = float(record.real_time_end) - float(start_time)
            #             else:
            #                 if resource_calendar_id.lunch_hour_to >= record.request_hour_from:
            #                     start_time = resource_calendar_id.lunch_hour_to
            #                 else:
            #                     start_time = record.request_hour_from
            #                 record.real_period = float(record.real_time_end) - float(start_time)
            #
            #         elif attendances and resource_calendar_id.calendar_type != '1':
            #             hour_to = attendances[-1].hour_to
            #             record.real_period = float(record.real_time_end) - float(record.request_hour_from)
            #         elif not attendances:
            #             deduct = 0
            #
            #             if float(record.request_hour_to) >= float(resource_calendar_id.lunch_hour_to):
            #                 deduct += resource_calendar_id.lunch_time
            #             if float(record.request_hour_to) >= float(resource_calendar_id.dinner_hour_to):
            #                 deduct += resource_calendar_id.dinner_time
            #             if float(record.request_hour_from) <= float(resource_calendar_id.lunch_hour_from):
            #                 start_time = record.request_hour_from
            #             elif float(record.request_hour_from) > float(resource_calendar_id.lunch_hour_from) and float(
            #                     record.request_hour_from) <= float(resource_calendar_id.lunch_hour_to):
            #                 start_time = record.resource_calendar_id.lunch_hour_to
            #             elif float(record.request_hour_from) > float(resource_calendar_id.lunch_hour_to) and float(
            #                     record.request_hour_from) <= float(resource_calendar_id.dinner_hour_from):
            #                 start_time = record.request_hour_from
            #             else:
            #                 start_time = record.request_hour_from
            #
            #             if float(record.real_time_end) <= float(resource_calendar_id.lunch_hour_from):
            #                 end_time = record.request_hour_to
            #             elif float(record.real_time_end) > float(resource_calendar_id.lunch_hour_from) and float(
            #                     record.real_time_end) <= float(resource_calendar_id.lunch_hour_to):
            #                 end_time = resource_calendar_id.lunch_hour_from
            #             elif float(record.real_time_end) <= float(resource_calendar_id.dinner_hour_from):
            #                 end_time = record.real_time_end
            #             else:
            #                 end_time = record.real_time_end
            #             record.real_period = float(end_time) - float(start_time) - deduct
            #     else:
            #         record.real_period = 0
            # else:
            #     record.real_period=0



    request_hour_from = fields.Selection([
        ('0', '0:00'), ('0.5', '0:30'),
        ('1', '1:00'), ('1.5', '1:30'),
        ('2', '2:00'), ('2.5', '2:30'),
        ('3', '3:00'), ('3.5', '3:30'),
        ('4', '4:00'), ('4.5', '4:30'),
        ('5', '5:00'), ('5.5', '5:30'),
        ('6', '6:00'), ('6.5', '6:30'),
        ('7', '7:00'), ('7.5', '7:30'),
        ('8', '8:00'), ('8.5', '8:30'),
        ('9', '9:00'), ('9.5', '9:30'),
        ('10', '10:00'), ('10.5', '10:30'),
        ('11', '11:00'), ('11.5', '11:30'),
        ('12', '12:00'), ('12.5', '12:30'),
        ('13', '13:00'), ('13.5', '13:30'),
        ('14', '14:00'), ('14.5', '14:30'),
        ('15', '15:00'), ('15.5', '15:30'),
        ('16', '16:00'), ('16.5', '16:30'),
        ('17', '17:00'), ('17.5', '17:30'),
        ('18', '18:00'), ('18.5', '18:30'),
        ('19', '19:00'), ('19.5', '19:30'),
        ('20', '20:00'), ('20.5', '20:30'),
        ('21', '21:00'), ('21.5', '21:30'),
        ('22', '22:00'), ('22.5', '22:30'),
        ('23', '23:00'), ('23.5', '23:30')], string='开始时间')
    request_hour_to = fields.Selection([
        ('0', '0:00'), ('0.5', '0:30'),
        ('1', '1:00'), ('1.5', '1:30'),
        ('2', '2:00'), ('2.5', '2:30'),
        ('3', '3:00'), ('3.5', '3:30'),
        ('4', '4:00'), ('4.5', '4:30'),
        ('5', '5:00'), ('5.5', '5:30'),
        ('6', '6:00'), ('6.5', '6:30'),
        ('7', '7:00'), ('7.5', '7:30'),
        ('8', '8:00'), ('8.5', '8:30'),
        ('9', '9:00'), ('9.5', '9:30'),
        ('10', '10:00'), ('10.5', '10:30'),
        ('11', '11:00'), ('11.5', '11:30'),
        ('12', '12:00'), ('12.5', '12:30'),
        ('13', '13:00'), ('13.5', '13:30'),
        ('14', '14:00'), ('14.5', '14:30'),
        ('15', '15:00'), ('15.5', '15:30'),
        ('16', '16:00'), ('16.5', '16:30'),
        ('17', '17:00'), ('17.5', '17:30'),
        ('18', '18:00'), ('18.5', '18:30'),
        ('19', '19:00'), ('19.5', '19:30'),
        ('20', '20:00'), ('20.5', '20:30'),
        ('21', '21:00'), ('21.5', '21:30'),
        ('22', '22:00'), ('22.5', '22:30'),
        ('23', '23:00'), ('23.5', '23:30')], string='结束时间')
    @api.depends('request_hour_to','request_hour_from')
    def compute_period(self):
        for record in self:
            record.period=0
            if record.apply_date and record.request_hour_from and record.request_hour_to:
                lunch_hour = 0
                dinner_time=0
                resource_calendar_id=record.employee_id.get_current_calendar_id(record.apply_date)
                if resource_calendar_id and record.employee_id.employee_type!='1':

                    attendances=record.employee_id.get_employee_attendance(record.apply_date)
                    lunch_hour = record.employee_id.resource_calendar_id.lunch_time
                    # 月薪没加班
                    if record.employee_id.employee_type not in ('2','3'):
                        record.period=0
                    #  日薪有考勤
                    elif attendances and record.employee_id.employee_type=='2' and resource_calendar_id.calendar_type  in ('1','2'):
                            # 日薪的话下班后才算加班
                            hour_to = attendances[-1].hour_to
                            request_hour_to=record.request_hour_to
                            if float(record.request_hour_from)<float(hour_to):
                                raise UserError('%s %s 加班开始时间不能早于下班时间2' % (record.employee_id.name,record.apply_date))
                            if record.request_hour_to>resource_calendar_id.dinner_hour_to:
                                if resource_calendar_id.dinner_hour_to>=record.request_hour_from:
                                    start_time=resource_calendar_id.dinner_hour_to
                                else:
                                    start_time=record.request_hour_from
                                record.period= float(request_hour_to) - float(start_time)

                            else:
                                record.period=0
                    elif attendances and record.employee_id.employee_type == '2' and resource_calendar_id.calendar_type =='3':
                        hour_to = attendances[0].hour_to
                        request_hour_to = float(record.request_hour_to)
                        request_hour_from = float(record.request_hour_from)
                        if float(request_hour_from) < 12:
                            request_hour_from = float(request_hour_from) + 24
                        if float(hour_to) < 12:
                            hour_to = float(hour_to) + 24
                        if float(record.request_hour_to) < 12:
                            request_hour_to = float(record.request_hour_to) + 24
                        if float(request_hour_from) < float(hour_to):
                            print (request_hour_from)
                            print (request_hour_to)
                            raise UserError('%s %s 加班开始时间不能早于下班时间3' % (record.employee_id.name,record.apply_date))
                        if resource_calendar_id.dinner_hour_to:
                            compare_time = float(resource_calendar_id.dinner_hour_to)
                        else:
                            compare_time = float(attendances[0].hour_to)
                        if compare_time < 12:
                            compare_time = compare_time + 24
                        if request_hour_to > compare_time:
                            if compare_time >= request_hour_from:
                                start_time = compare_time
                            else:
                                start_time = request_hour_from
                            record.period = float(request_hour_to) - float(start_time)

                    # 没考勤或者是时薪
                    elif not attendances or record.employee_id.employee_type=='3':
                        request_hour_to=record.request_hour_to
                        lunch_hour_to=resource_calendar_id.lunch_hour_to
                        lunch_hour_from=resource_calendar_id.lunch_hour_from
                        if resource_calendar_id.calendar_type == '3' and float(record.request_hour_to)<=float(record.request_hour_from):
                            request_hour_to = float(record.request_hour_to) + 24
                            lunch_hour_to=float(resource_calendar_id.lunch_hour_to)+24
                            lunch_hour_from=float(resource_calendar_id.lunch_hour_from)+24
                        deduct=0
                        if float(request_hour_to) >= float(lunch_hour_to) and float(lunch_hour_from)>=float(record.request_hour_from):
                            deduct += resource_calendar_id.lunch_time
                        if resource_calendar_id.dinner_hour_from and resource_calendar_id.dinner_hour_to and float(request_hour_to) >= float(resource_calendar_id.dinner_hour_to) and float(resource_calendar_id.dinner_hour_from)>= float(record.request_hour_from):
                            deduct += resource_calendar_id.dinner_time
                        if float(record.request_hour_from)<=float(lunch_hour_from):
                            start_time=record.request_hour_from
                        elif float(record.request_hour_from)>float(lunch_hour_from)  and float(record.request_hour_from)<=float(lunch_hour_to):
                            start_time=lunch_hour_to
                        elif float(record.request_hour_from)>float(lunch_hour_to) and float(record.request_hour_from)<=float(resource_calendar_id.dinner_hour_from):
                            start_time=record.request_hour_from
                        else:
                            start_time = record.request_hour_from

                        if float(request_hour_to)<=float(lunch_hour_from):
                            end_time=request_hour_to
                        elif float(request_hour_to)>float(lunch_hour_from) and float(request_hour_to)<=float(lunch_hour_to):
                            end_time=resource_calendar_id.lunch_hour_from
                        elif float(request_hour_to)<=float(resource_calendar_id.dinner_hour_from):
                            end_time=request_hour_to
                        else:
                            end_time=request_hour_to
                        record.period = float(end_time) - float(start_time)-deduct

                    # elif attendances and resource_calendar_id.calendar_type == '3':
                    #     hour_to = attendances[-1].hour_to
                    #     record.period = float(record.request_hour_to) - float(record.request_hour_from)
                else:
                    record.period = 0
            else:
                record.period = 0
    remark=fields.Char(string=u'理由',required='1')
    period=fields.Float(string='加班时长',compute='compute_period')


    @api.constrains('request_hour_from', 'request_hour_to')
    def check_dates(self):
        for r in self:
            request_hour_from=r.request_hour_from
            request_hour_to=r.request_hour_to
            resource_calendar_id = r.employee_id.get_current_calendar_id(r.apply_date)
            if resource_calendar_id.calendar_type=='3':
                request_hour_to=float(r.request_hour_to)+24

            if float(request_hour_from)>float(request_hour_to):
                raise ValidationError('%s  %s 加班开始时间不能小于结束时间' % (r.employee_id.name,r.apply_date))




    @api.constrains('employee_id', 'apply_date')
    def check_employee_overtime(self):
        for r in self:
            o=self.env['hr.overtime'].search([('employee_id','=',r.employee_id.id),('apply_date','=',r.apply_date)])
            if len(o)>1:
                raise ValidationError('%s在%s 已经有加班单' % (r.employee_id.name,r.apply_date))




